using System;
using System.Windows.Forms;
using FBroSharp;
using FBroSharp.Lib;
using FBroSharp.Event;
using FBroSharp.Const;
using FBroSharp.Value;
using FBroSharp.DataType;
using FBroSharp.Callback;

namespace 文件下载管理器
{
    /// <summary>
    /// 浏览器事件处理类
    /// ⚠️ 必须是独立文件！不要放在 Form1.cs 中！
    /// </summary>
    public class BrowserEvent : FBroSharpBrowserEvent
    {
        private Form1 _form;

        public BrowserEvent(Form1 form)
        {
            _form = form;
        }

        /// <summary>
        /// ⚠️ REQUIRED: 浏览器创建完成（两个参数！）
        /// </summary>
        public override void OnAfterCreated(IFBroSharpBrowser browser, IFBroSharpDictionaryValue extrainfo)
        {
            _form.UpdateStatus($"浏览器已就绪 (ID: {browser.GetIdentifier()})");
            Console.WriteLine($"[BrowserEvent] 浏览器创建完成，ID：{browser.GetIdentifier()}");
        }

        /// <summary>
        /// ⚠️ CRITICAL: 弹窗控制 - 防止新窗口打开
        /// </summary>
        public override bool OnBeforePopup(
            IFBroSharpBrowser browser, 
            IFBroSharpFrame frame, 
            string target_url, 
            string target_frame_name,
            FBroSharpWindowOpenDisposition target_disposition, 
            bool user_gesture, 
            FBroSharpPopupfeatures popupFeatures, 
            ref FBroSharpWindowsInfo windowInfo,
            ref FBroSharpBrowserSetting settings,
            ref bool no_javascript_access, 
            IFBroSharpUseExtraData user_settings)
        {
            // 在当前窗口打开链接
            frame.LoadURL(target_url);
            return true; // true = 阻止弹窗
        }

        /// <summary>
        /// URL 变更
        /// </summary>
        public override void OnAddressChange(IFBroSharpBrowser browser, IFBroSharpFrame frame, string url)
        {
            if (frame.IsMain())
            {
                _form.UpdateAddressBar(url);
            }
        }

        /// <summary>
        /// 标题变更
        /// </summary>
        public override void OnTitleChange(IFBroSharpBrowser browser, string title)
        {
            _form.UpdateTitle(title);
        }

        /// <summary>
        /// 加载状态变更
        /// </summary>
        public override void OnLoadingStateChange(IFBroSharpBrowser browser, bool isLoading, bool canGoBack, bool canGoForward)
        {
            _form.UpdateLoadingState(isLoading);
        }

        /// <summary>
        /// 开始加载
        /// </summary>
        public override void OnLoadStart(IFBroSharpBrowser browser, IFBroSharpFrame frame, FBroSharpTransitionType transition_type)
        {
            if (frame.IsMain())
            {
                _form.UpdateStatus($"开始加载: {frame.GetURL()}");
            }
        }

        /// <summary>
        /// 加载完成
        /// </summary>
        public override void OnLoadEnd(IFBroSharpBrowser browser, IFBroSharpFrame frame, int httpStatusCode)
        {
            if (frame.IsMain())
            {
                _form.UpdateStatus($"加载完成 (HTTP {httpStatusCode})");
            }
        }

        /// <summary>
        /// 加载错误
        /// </summary>
        public override void OnLoadError(IFBroSharpBrowser browser, IFBroSharpFrame frame, 
            int errorCode, string errorText, string failedUrl)
        {
            if (frame.IsMain())
            {
                _form.UpdateStatus($"加载失败: {errorText}");
            }
        }

        /// <summary>
        /// ⚠️ CRITICAL: 下载事件 - 文件下载管理的核心！
        /// 在事件层提取下载数据，然后传递到UI层
        /// </summary>
        public override void OnBeforeDownload(IFBroSharpBrowser browser, IFBroSharpDownloadItem download_item, 
            string suggested_name, IFBroSharpBeforeDownloadCallback callback)
        {
            // 在事件层提取数据
            uint downloadId = download_item.GetDownloadId();
            long totalBytes = download_item.GetTotalBytes();
            
            // 传递提取的数据到UI层（使用suggested_name作为唯一标识）
            _form.HandleBeforeDownload(downloadId, suggested_name, totalBytes, callback);
        }

        /// <summary>
        /// ⚠️ CRITICAL: 下载进度更新
        /// 在事件层提取下载数据，然后传递到UI层
        /// </summary>
        public override void OnDownloadUpdated(IFBroSharpBrowser browser, IFBroSharpDownloadItem download_item, 
            IFBroSharpDownloadItemCallback callback)
        {
            // 在事件层提取数据
            uint downloadId = download_item.GetDownloadId();
            string suggestedName = download_item.GetSuggestedFileName();
            string fullPath = download_item.GetFullPath();
            long receivedBytes = download_item.GetReceivedBytes();
            long totalBytes = download_item.GetTotalBytes();
            int percentComplete = download_item.GetPercentComplete();
            long currentSpeed = download_item.GetCurrentSpeed();
            bool isComplete = download_item.IsComplete();
            bool isCanceled = download_item.IsCanceled();
            bool isInProgress = download_item.IsInProgress();
            
            // 传递提取的数据到UI层
            _form.HandleDownloadUpdated(downloadId, suggestedName, fullPath, 
                receivedBytes, totalBytes, percentComplete, currentSpeed, 
                isComplete, isCanceled, isInProgress, callback);
        }

        /// <summary>
        /// 浏览器关闭前
        /// </summary>
        public override void OnBeforeClose(IFBroSharpBrowser browser)
        {
            Console.WriteLine("[BrowserEvent] 浏览器即将关闭");
        }

        /// <summary>
        /// 是否可以关闭浏览器
        /// </summary>
        public override bool DoClose(IFBroSharpBrowser browser)
        {
            return false; // false = 允许关闭
        }
    }
}

